package com.hepinghospital.user.ui.activity.home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.ui.PayActivity;
import com.hepinghospital.user.ui.widget.CustomPopWindow;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.CloudDoctorResponse;
import com.rest.response.DicResponse;
import com.rest.response.Doctor;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.DpUtil;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UtilString;


/**
 * Created by HP on 2020/2/20.
 */

public class BookDoctorByDateActivity extends BaseActivity {

    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.doctor_recyclerView)
    RecyclerView doctor_recyclerView;
    @BindView(R.id.date_recyclerView)
    RecyclerView date_recyclerView;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.btn_search)
    ImageView btnSearch;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.icon1)
    ImageView icon1;
    @BindView(R.id.icon2)
    ImageView icon2;
    @BindView(R.id.icon3)
    ImageView icon3;
    @BindView(R.id.tv_keshi)
    TextView tvKeshi;
    @BindView(R.id.tv_zhichen)
    TextView tvZhichen;
    @BindView(R.id.tv_chufang)
    TextView tvChufang;

    List<DateTime> dateList = new ArrayList<>();
    List<Doctor> doctorList = new ArrayList<>();

    DoctorAdapter doctorAdapter;
    DateAdapter dateAdapter;

    int current = 1;
    String currentString = "", currentId = "";
    String deptId = "0", codeType = "", code = "";

    private String isPrescription = "";


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_book_docot_date;
    }

    @Override
    protected void initViews() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        doctor_recyclerView.setLayoutManager(manager);
        doctorAdapter = new DoctorAdapter();
        doctor_recyclerView.setAdapter(doctorAdapter);
        doctor_recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = DpUtil.dip2px(BookDoctorByDateActivity.this, 8);
            }
        });

        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> getDoctorList(currentId, currentString, "", "", isPrescription, code));
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            current++;
            getDoctorList(currentId, currentString, "", "", isPrescription, code);
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(BookDoctorByDateActivity.this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        date_recyclerView.setLayoutManager(linearLayoutManager);
        dateAdapter = new DateAdapter();
        date_recyclerView.setAdapter(dateAdapter);
        date_recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.right = DpUtil.dip2px(BookDoctorByDateActivity.this, 8);
            }
        });
    }

    @Override
    protected void initData() {
        current = 1;
        getDoctorList(currentId, currentString, "", "", isPrescription, code);
        getDateList();
    }

    class DoctorAdapter extends RecyclerView.Adapter<DoctorAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            return new Holder(LayoutInflater.from(BookDoctorByDateActivity.this).inflate(R.layout.item_book_doctor_online, parent, false));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                Bundle bundleCloud = new Bundle();
                bundleCloud.putSerializable(UIConstants.OBJ_Doctor, doctorList.get(position));
                bundleCloud.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_1);
                startActivity(PayActivity.class, bundleCloud);
            });
            holder.tv_level.setText(doctorList.get(position).jobTitleName);
            holder.tv_skill.setText("擅长:" + doctorList.get(position).docGoodAtNames);
            holder.tv_star.setText(doctorList.get(position).score);
            holder.tv_name.setText(doctorList.get(position).docName);
            ImageLoaderHelper.getInstance().GlideCircleImageLoader(BookDoctorByDateActivity.this, doctorList.get(position).thumbnailUrl, holder.img_head);
            if (doctorList.get(position).isPrescription == 1) {
                holder.tv_recipel.setText("处方");
                holder.tv_recipel.setTextColor(Color.parseColor("#ff209187"));
            } else {
                holder.tv_recipel.setText("非处方");
                holder.tv_recipel.setTextColor(Color.parseColor("#ffd5d5d5"));
            }
            if (!UtilString.isEmpty(doctorList.get(position).num)) {
                holder.tv_turnNum.setVisibility(View.VISIBLE);
                holder.tv_turnNum.setText("咨询数 " + doctorList.get(position).num);
            } else {
                holder.tv_turnNum.setVisibility(View.GONE);
            }
            if (!UtilString.isEmpty(doctorList.get(position).deptName)) {
                holder.tv_deptName.setText(doctorList.get(position).deptName);
            } else {
                holder.tv_deptName.setVisibility(View.GONE);
            }
            if ("0".equals(doctorList.get(position).isRecommend)) {
                holder.ivRecommend.setVisibility(View.GONE);
            } else {
                holder.ivRecommend.setVisibility(View.VISIBLE);
            }

            holder.ratingBar.setRating(Float.parseFloat(doctorList.get(position).score));
        }

        @Override
        public int getItemCount() {
            return doctorList.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_level, tv_recipel, tv_deptName, tv_skill, tv_star, tv_turnNum;
            ImageView img_head, ivRecommend;
            RatingBar ratingBar;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_level = itemView.findViewById(R.id.tv_level);
                tv_recipel = itemView.findViewById(R.id.tv_recipel);
                tv_deptName = itemView.findViewById(R.id.tv_deptName);
                tv_skill = itemView.findViewById(R.id.tv_skill);
                tv_star = itemView.findViewById(R.id.tv_star);
                img_head = itemView.findViewById(R.id.img_head);
                ratingBar = itemView.findViewById(R.id.ratingBar);
                tv_turnNum = itemView.findViewById(R.id.tv_turn_num);
                ivRecommend = itemView.findViewById(R.id.iv_recommend);
            }
        }
    }


    class DateAdapter extends RecyclerView.Adapter<DateAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(BookDoctorByDateActivity.this).inflate(R.layout.item_book_date, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(@NotNull Holder holder, final int position) {
            if (dateList.get(position).isSelect) {
                holder.tv_date.setTextColor(getResources().getColor(R.color.white));
                holder.tv_time.setTextColor(getResources().getColor(R.color.white));
                holder.tv_all.setTextColor(getResources().getColor(R.color.white));
                holder.container.setBackgroundResource(R.drawable.item_bg_green);
            } else {
                holder.tv_date.setTextColor(getResources().getColor(R.color.lightBlack));
                holder.tv_time.setTextColor(getResources().getColor(R.color.lightBlack));
                holder.tv_all.setTextColor(getResources().getColor(R.color.lightBlack));
                holder.container.setBackgroundResource(R.drawable.item_bg_grey);
            }
            if (position == 0) {
                holder.tv_date.setVisibility(View.INVISIBLE);
                holder.tv_time.setVisibility(View.INVISIBLE);
                holder.tv_all.setVisibility(View.VISIBLE);
            } else {
                holder.tv_date.setVisibility(View.VISIBLE);
                holder.tv_time.setVisibility(View.VISIBLE);
                holder.tv_all.setVisibility(View.INVISIBLE);
                holder.tv_date.setText(dateList.get(position).date);
                holder.tv_time.setText(dateList.get(position).time);
            }
            holder.itemView.setOnClickListener(v -> {
                if (position == 0) {
                    getDoctorList(currentId, currentString, "", "", isPrescription, code);
                } else {
                    getDoctorList(currentId, currentString, dateList.get(position).allDate, dateList.get(position).timeId, isPrescription, code);
                }
                for (int i = 0; i < dateList.size(); i++) {
                    dateList.get(i).isSelect = false;
                }
                dateList.get(position).isSelect = true;
                notifyDataSetChanged();
            });
        }

        @Override
        public int getItemCount() {
            return dateList.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_date, tv_time, tv_all;
            RelativeLayout container;

            public Holder(View itemView) {
                super(itemView);
                tv_date = itemView.findViewById(R.id.tv_date);
                tv_time = itemView.findViewById(R.id.tv_time);
                tv_all = itemView.findViewById(R.id.tv_all);
                container = itemView.findViewById(R.id.container);
            }
        }
    }


    private void getDateList() {
        dateList.add(new DateTime());
        for (int i = 1; i < 15; i++) {
            for (int j = 0; j < 2; j++) {
                Calendar c = Calendar.getInstance();
                DateTime dateTime = new DateTime();
                int day1 = c.get(Calendar.DATE);
                c.set(Calendar.DATE, day1 + i);
                dateTime.date = getTime(c.getTime());
                dateTime.allDate = getAllTime(c.getTime());
                if (j == 0) {
                    dateTime.time = getDay(c) + "上午";
                    dateTime.timeId = "am";
                } else {
                    dateTime.time = getDay(c) + "下午";
                    dateTime.timeId = "pm";
                }
                dateList.add(dateTime);
            }
        }
        dateList.get(0).isSelect = true;
    }


    private void getDoctorList(String id, String content, String date, String time, String isPrescription, String code) {
        RestProxy.getInstance().getCloudDoctorListIsPrescription(id, content, date, time, "3", current + "", "20", isPrescription, code, new BaseObserver<CloudDoctorResponse>() {
            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(BookDoctorByDateActivity.this, e);
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onSuccess(CloudDoctorResponse doctorResponse) {
                doctorList.clear();
                doctorList.addAll(doctorResponse.records);
                doctorAdapter.notifyDataSetChanged();
                refreshLayout.finishRefresh(true);
            }
        });
    }

    static class DateTime {
        public String date;
        public String time;
        String timeId;
        String allDate;
        boolean isSelect = false;
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        @SuppressLint("SimpleDateFormat") SimpleDateFormat format = new SimpleDateFormat("MM-dd");
        return format.format(date);
    }

    private String getAllTime(Date date) {//可根据需要自行截取数据显示
        @SuppressLint("SimpleDateFormat") SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private String getDay(Calendar c) {
        String[] arr = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        return arr[c.get(Calendar.DAY_OF_WEEK) - 1];
    }

    List<DicResponse> list = new ArrayList<>();
    private CustomPopWindow mPopWindow;
    AddMedicineAdapter adapter;

    @OnClick(R.id.btn_keshi)
    void btn_keshi() {
//        icon1.setImageResource(R.mipmap.icon_pop);
//        icon3.setImageResource(R.mipmap.icon_pop);
//        icon2.setImageResource(R.mipmap.icon_down);
        tvZhichen.setTextColor(ContextCompat.getColor(this, R.color.commonGrey));
        tvKeshi.setTextColor(ContextCompat.getColor(this, R.color.mainBlue));
        tvChufang.setTextColor(ContextCompat.getColor(this, R.color.commonGrey));
        showPopListView(tvKeshi, 0);
    }

    @OnClick(R.id.btn_zhichen)
    void btn_zhichen() {
//        icon1.setImageResource(R.mipmap.icon_pop);
//        icon3.setImageResource(R.mipmap.icon_down);
//        icon2.setImageResource(R.mipmap.icon_pop);
        tvZhichen.setTextColor(ContextCompat.getColor(this, R.color.mainBlue));
        tvKeshi.setTextColor(ContextCompat.getColor(this, R.color.commonGrey));
        tvChufang.setTextColor(ContextCompat.getColor(this, R.color.commonGrey));

        showPopListView(tvZhichen, 1);

    }

    @OnClick(R.id.btn_search)
    void btn_search() {
        Bundle bundle = new Bundle();
        bundle.putInt("type", 3);
        bundle.putString("fromType", "fromCloud");
        startActivity(SearchDoctorActivity.class, bundle);
    }

    @OnClick(R.id.btn_chufang)
    void tv_chufang() {
//        icon1.setImageResource(R.mipmap.icon_down);
//        icon3.setImageResource(R.mipmap.icon_pop);
//        icon2.setImageResource(R.mipmap.icon_pop);
        tvZhichen.setTextColor(ContextCompat.getColor(this, R.color.commonGrey));
        tvKeshi.setTextColor(ContextCompat.getColor(this, R.color.commonGrey));
        tvChufang.setTextColor(ContextCompat.getColor(this, R.color.mainBlue));
        showPopListView(tvZhichen, 2);
    }

    private void showPopListView(View view, int type) {
        @SuppressLint("InflateParams") View contentView = LayoutInflater.from(BookDoctorByDateActivity.this).inflate(R.layout.pop_window, null);
        RecyclerView recyclerView = contentView.findViewById(R.id.recyclerView);
        LinearLayoutManager manager = new LinearLayoutManager(BookDoctorByDateActivity.this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new AddMedicineAdapter(this, type);
        recyclerView.setAdapter(adapter);
        if (type == 1) {
            //职称信息
            getDictList();
        } else if (type == 0) {
            //按照科室
            getDepartmentList();
        } else {
            list.clear();
            list.add(new DicResponse("全部", "0"));
            list.add(new DicResponse("处方", "1"));
            list.add(new DicResponse("非处方", "2"));
            adapter.notifyDataSetChanged();
        }

        //创建并显示popWindow
        mPopWindow = new CustomPopWindow.PopupWindowBuilder(BookDoctorByDateActivity.this)
                .setView(contentView)
                .setTouchable(true)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, DpUtil.dip2px(BookDoctorByDateActivity.this, 300)) // 显示大小
                .create()
                .showAsDropDown(view, 0, 0, Gravity.CENTER);
    }


    class AddMedicineAdapter extends RecyclerView.Adapter<AddMedicineAdapter.Holder> {
        int type;
        private Context context;

        AddMedicineAdapter(Context context, int type) {
            this.context = context;
            this.type = type;
        }

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(BookDoctorByDateActivity.this).inflate(R.layout.item_textview, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                if (type == 1) {
                    //按照职称查询
                    if (position == 0) {
                        code = list.get(position).code;
                        tvZhichen.setText("职称");
                    } else {
                        code = list.get(position).code;
                        tvZhichen.setText(list.get(position).name);
                    }
                    tvZhichen.setTextColor(ContextCompat.getColor(context, R.color.mainBlue));
                    getDoctorList(currentId, currentString, "", "", isPrescription, code);
                    mPopWindow.dissmiss();
                } else if (type == 0) {
                    //按照科室查询
                    if (position == 0) {
                        currentId = "";
                        tvKeshi.setText("科室");
                    } else {
                        currentId = list.get(position).id;
                        tvKeshi.setText(list.get(position).name);
                    }
                    tvKeshi.setTextColor(ContextCompat.getColor(context, R.color.mainBlue));
                    getDoctorList(currentId, currentString, "", "", isPrescription, code);
                    mPopWindow.dissmiss();
                } else {
                    codeType = list.get(position).code;
                    tvChufang.setTextColor(ContextCompat.getColor(context, R.color.mainBlue));
                    if ("1".equals(codeType)) {

                        tvChufang.setText("处方");
                        isPrescription = "1";
                    } else if ("2".equals(codeType)) {
                        tvChufang.setText("非处方");
                        isPrescription = "0";
                    } else {
                        tvChufang.setText("处方权限");
                        isPrescription = "";
                    }
                    getDoctorList(currentId, currentString, "", "", isPrescription, code);
                    mPopWindow.dissmiss();
                }
            });
            holder.tv_name.setText(list.get(position).name);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.text);
            }
        }
    }

    private void getDictList() {
        RestProxy.getInstance().getDicList(new BaseObserver<List<DicResponse>>() {

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(BookDoctorByDateActivity.this, e);
            }

            @Override
            public void onSuccess(List<DicResponse> result) {
                list.clear();
                list.add(new DicResponse("全部", ""));
                list.addAll(result);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void getDepartmentList() {
        RestProxy.getInstance().getDepartment2List(new Observer<List<DicResponse>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<DicResponse> dicResponses) {
                list.clear();
                list.add(new DicResponse("全部", ""));
                list.addAll(dicResponses);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                refreshLayout.finishRefresh(false);
                ToastUtil.onError(BookDoctorByDateActivity.this, e);

            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }
}
